package service

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/shopspring/decimal"
	"gorm.io/gorm"
	"mojieshi/define"
	"mojieshi/models"
	"net/http"
	"strconv"
	"strings"
	"time"
)

// 获取服务订单列表
type PrList struct {
	BusinessLogo    string          `json:"business_logo"`
	BusinessName    string          `json:"business_name"`
	Aid             int             `json:"aid"`
	Createtime      int             `json:"createtime"` //创建时间
	Status          int             `json:"status"`     //0未支付;1已支付;2申请退款；3已驳回；4已退款5关闭
	Ordernum        string          `json:"ordernum"`   //订单号
	ID              int             `json:"id"`
	Payorderid      int             `json:"payorderid"`                        //订单支付表id
	Totalprice      decimal.Decimal `json:"totalprice"`                        //总金额
	Proid           int             `json:"proid"`                             //商品ID
	Pic             string          `json:"pic"`                               //商品主图
	Ggid            int             `json:"ggid"`                              //规格ID
	Ggname          string          `json:"ggname"`                            //规格名称
	Num             int             `json:"num"`                               //购买数量
	Name            string          `json:"name"`                              //商品名称
	SellPrice       float64         `json:"sell_price"`                        //销售价
	Paytypeid       int             `gorm:"type:int(10);" json:"paytypeid"`    //2余额支付 1微信支付
	Paytype         string          `gorm:"type:varchar(255);" json:"paytype"` //支付方式文本
	CreateOrderSign string          `json:"create_order_sign"`                 //支付签名
}
type PrListData struct {
	List    PrList                 `json:"list"`
	ProList []models.MFuwuOrderLog `json:"pro_list"`
}

func GetOrderList(c *gin.Context) {
	var jsonData Newdata
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonDataX, "")
		return
	}
	var list []PrList
	var count int64
	if jsonData.Page == 0 {
		jsonData.Page = -1
	}
	if jsonData.Limit == 0 {
		jsonData.Limit = -1
	}
	offsetVal := (jsonData.Page - 1) * jsonData.Limit
	if jsonData.Page == -1 && jsonData.Limit == -1 {
		offsetVal = -1
	}
	selectData1 := "m_admin_set.name as business_name,m_admin_set.logo as business_logo,m_fuwu_order.id,m_fuwu_order.aid,m_fuwu_order.createtime,m_fuwu_order.status" +
		",m_fuwu_order.ordernum,m_fuwu_order.payorderid,m_fuwu_order.totalprice,m_fuwu_order.num" +
		",m_fuwu_order.paytypeid,m_fuwu_order.paytype,m_payorder.create_order_sign"
	tx := models.DB.Table("m_fuwu_order").Select(selectData1).Joins("left join m_admin_set on m_admin_set.aid=m_fuwu_order.aid").Joins("left join m_payorder on m_payorder.id=m_fuwu_order.payorderid")
	tx = tx.Where("m_fuwu_order.mid=? AND m_fuwu_order.user_delete=?", jsonData.Mid, 0)
	if jsonData.Type > -1 {
		tx = tx.Where("m_fuwu_order.status=?", jsonData.Type)
	}
	tx = tx.Count(&count).Limit(jsonData.Limit).Offset(offsetVal).Order("m_fuwu_order.id desc").Find(&list)
	if tx.Error != nil {
		define.Response.ResultFail(c, 10001, define.JsonDataX, "")
		return
	}
	var ListData []PrListData
	for _, v := range list {
		var OrderLogList []models.MFuwuOrderLog
		err = models.DB.Model(new(models.MFuwuOrderLog)).Where("orderid", v.ID).Find(&OrderLogList).Error
		if err != nil {
			define.Response.ResultFail(c, 10002, define.JsonDataX, "")
			return
		}
		one := PrListData{
			List:    v,
			ProList: OrderLogList,
		}
		ListData = append(ListData, one)
	}
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data":    ListData,
		"count":   count,
	})
}

// 取消服务订单
func CancelFuOrder(c *gin.Context) {
	var jsonData Newdata
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonDataX, "")
		return
	}
	var orderData models.MFuwuOrder
	var count int64
	err = models.DB.Model(new(models.MFuwuOrder)).Where("id=?", jsonData.Id).Count(&count).First(&orderData).Error
	if err != nil {
		define.Response.ResultFail(c, 10001, define.JsonDataX, "")
		return
	}
	//判断当前订单是否存在以及状态是否为0
	if count < 0 {
		define.Response.ResultFail(c, 10002, "订单未查询到！", "")
		return
	}
	if orderData.Status != 0 {
		define.Response.ResultFail(c, 10003, "该订单已无法取消！", "")
		return
	}
	tx := models.DB.Begin() //开启事务
	//修改订单状态
	var editData = map[string]interface{}{
		"status": 5,
	}
	err = tx.Model(new(models.MFuwuOrder)).Where("id=?", jsonData.Id).Updates(&editData).Error
	if err != nil {
		define.Response.ResultFail(c, 10004, define.JsonDataX, "")
		tx.Rollback()
		return
	}
	//修改支付表状态
	err = tx.Model(new(models.MPayOrder)).Where("orderid=?", jsonData.Id).Update("status", 2).Error
	if err != nil {
		define.Response.ResultFail(c, 10004, define.JsonDataX, "")
		tx.Rollback()
		return
	}
	//删除服务明细表
	err = FuwuOrderGoodsDel(jsonData.Id, tx)
	if err != nil {
		define.Response.ResultFail(c, 10005, define.JsonDataX, "")
		tx.Rollback()
		return
	}
	//回滚用户的优惠券
	if orderData.CouponRid != "" {
		couPon := strings.Split(orderData.CouponRid, ",")
		for _, s := range couPon {
			n, _ := strconv.Atoi(s)
			err = tx.Model(new(models.MCouponRecord)).Where("id = ?", n).Update("status", 0).Error
			if err != nil {
				define.Response.ResultFail(c, 10006, err.Error(), "")
				tx.Rollback()
				return
			}
		}
	}
	//回滚积分
	if orderData.Scoredkscore > 0 {
		cur := models.ScoreAdd(tx, orderData.Mid, orderData.Scoredkscore, orderData.Aid, "订单关闭返回积分，订单号："+orderData.Ordernum)
		if cur == 2 {
			define.Response.ResultFail(c, 10007, err.Error(), "")
			tx.Rollback()
			return
		}
	}
	tx.Commit() //关闭事务
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data":    "",
		"msg":     "成功！",
	})
}

// 查询是否存在服务明细有就删除
func FuwuOrderGoodsDel(id int, tx *gorm.DB) error {
	var roltlist []models.MFuwuOrderGoods
	var count int64
	err := models.DB.Model(new(models.MFuwuOrderGoods)).Where("orderid=? AND status=?", id, 0).Count(&count).Find(&roltlist).Error
	if err != nil {
		return err
	}
	//判断是否有数据
	if count > 0 {
		tx.Where("orderid=?", id).Delete(models.MFuwuOrderGoods{})
	}
	return nil
}

// 删除服务订单
func DelFuOrder(c *gin.Context) {
	var jsonData Newdata
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonDataX, "")
		return
	}
	var orderData models.MFuwuOrder
	var count int64
	err = models.DB.Model(new(models.MFuwuOrder)).Where("id=?", jsonData.Id).Count(&count).First(&orderData).Error
	if err != nil {
		define.Response.ResultFail(c, 10001, define.JsonDataX, "")
		return
	}
	//判断当前订单是否存在以及状态是否为0
	if count < 0 {
		define.Response.ResultFail(c, 10002, "订单未查询到！", "")
		return
	}
	tx := models.DB.Begin() //开启事务
	//修改订单状态
	var editData = map[string]interface{}{
		"user_delete": 1,
	}
	err = tx.Model(new(models.MFuwuOrder)).Where("id=?", jsonData.Id).Updates(&editData).Error
	if err != nil {
		define.Response.ResultFail(c, 10004, define.JsonDataX, "")
		tx.Rollback()
		return
	}
	tx.Commit() //关闭事务
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data":    "",
		"msg":     "成功！",
	})
}

type ShopOrderShow struct {
	Show         models.MFuwuOrder      `json:"show"`
	ProList      []models.MFuwuOrderLog `json:"pro_list"`
	BusinessData BusinessData           `json:"business_data"`
	Juan         models.MJuanZeng       `json:"juan"`
}
type BusinessData struct {
	Name  string `json:"name"`  //
	Logo  string `json:"logo"`  //
	Kfurl string `json:"kfurl"` //
}

// 获取订单详情
func GetFuOrderShow(c *gin.Context) {
	var jsonData models.MFuwuOrder
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonDataX, "")
		return
	}
	var ReturnData ShopOrderShow
	err = models.DB.Model(new(models.MFuwuOrder)).Where("id=?", jsonData.ID).First(&ReturnData.Show).Error
	if err != nil {
		define.Response.ResultFail(c, 10001, define.JsonDataX, "")
		return
	}
	err = models.DB.Model(new(models.MFuwuOrderLog)).Where("orderid=?", jsonData.ID).Find(&ReturnData.ProList).Error
	if err != nil {
		define.Response.ResultFail(c, 10002, define.JsonDataX, "")
		return
	}
	var adminData models.MAdminSet
	err = models.DB.Model(new(models.MAdminSet)).Where("aid=?", ReturnData.Show.Aid).Find(&adminData).Error
	if err != nil {
		define.Response.ResultFail(c, 10003, define.JsonDataX, "")
		return
	}
	if define.FloatDecimal(ReturnData.Show.JuanPrice) > 0 {
		err = models.DB.Model(new(models.MJuanZeng)).Where("orderid=?", jsonData.ID).First(&ReturnData.Juan).Error
		if err != nil {
			define.Response.ResultFail(c, 10002, define.JsonDataX, "")
			return
		}
	}
	ReturnData.BusinessData.Logo = adminData.Logo
	ReturnData.BusinessData.Name = adminData.Name
	ReturnData.BusinessData.Kfurl = adminData.Kfurl
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data":    ReturnData,
	})
}

// 关闭服务订单
func CloseFuOrder(c *gin.Context) {
	//获取设置信息
	var ShopSetData models.MAdminSet
	err := models.DB.Model(new(models.MAdminSet)).Where("aid=?", 1).First(&ShopSetData).Error
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonDataX, "")
		return
	}
	//获取订单超时的时间
	curTime := int(time.Now().Unix()) - ShopSetData.Autoclose

	//查询超时未支付订单
	var payData []models.MFuwuOrder
	err = models.DB.Model(new(models.MFuwuOrder)).Where("aid=? AND createtime<? AND status=?", 1, curTime, 0).Find(&payData).Error
	if err != nil {
		define.Response.ResultFail(c, 10001, err.Error(), "")
		return
	}

	tx := models.DB.Begin()
	var payIds []int
	for _, v := range payData {
		payIds = append(payIds, v.ID)
	}
	//使用IN批量修改数据来关闭订单
	err = tx.Model(new(models.MFuwuOrder)).Where("id IN ?", payIds).Update("status", 5).Error
	if err != nil {
		define.Response.ResultFail(c, 10002, err.Error(), "")
		tx.Rollback()
		return
	}
	//关闭支付表
	err = tx.Model(new(models.MPayOrder)).Where("orderid IN ?", payIds).Update("status", 2).Error
	if err != nil {
		define.Response.ResultFail(c, 10003, err.Error(), "")
		tx.Rollback()
		return
	}
	//回滚用户的数据
	for _, v := range payData {
		//回滚用户的优惠券
		if v.CouponRid != "" {
			couPon := strings.Split(v.CouponRid, ",")
			for _, s := range couPon {
				n, _ := strconv.Atoi(s)
				err = tx.Model(new(models.MCouponRecord)).Where("id = ?", n).Update("status", 0).Error
				if err != nil {
					define.Response.ResultFail(c, 10004, err.Error(), "")
					tx.Rollback()
					return
				}
			}
		}
		//回滚积分
		if v.Scoredkscore > 0 {
			cur := models.ScoreAdd(tx, v.Mid, v.Scoredkscore, v.Aid, "订单关闭返回积分，订单号："+v.Ordernum)
			if cur == 2 {
				define.Response.ResultFail(c, 10005, err.Error(), "")
				tx.Rollback()
				return
			}
		}
		//删除服务明细表
		err = FuwuOrderGoodsDel(v.ID, tx)
		if err != nil {
			define.Response.ResultFail(c, 10006, define.JsonDataX, "")
			tx.Rollback()
			return
		}
	}
	tx.Commit() //结束事务
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data":    "成功",
	})
}

// 关闭预约订单
func CloseYuYue(c *gin.Context) {
	//获取设置信息
	var ShopSetData models.MAdminSet
	err := models.DB.Model(new(models.MAdminSet)).Where("aid=?", 1).First(&ShopSetData).Error
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonDataX, "")
		return
	}
	//获取预约超时的时间
	curTime := int(time.Now().Unix()) - ShopSetData.YueEnd
	//查询超时未完成预约
	var YueData []models.MFuwuYu
	err = models.DB.Model(new(models.MFuwuYu)).Where("aid=? AND status<? AND yu_yue_time<?", 1, 3, curTime).Find(&YueData).Error
	if err != nil {
		define.Response.ResultFail(c, 10001, err.Error(), "")
		return
	}
	tx := models.DB.Begin()
	var payIds []int
	for _, v := range YueData {
		payIds = append(payIds, v.ID)
	}
	//使用IN批量修改数据来关闭订单
	var editData = map[string]interface{}{
		"status":  3,
		"endtime": int(time.Now().Unix()),
	}
	err = tx.Model(new(models.MFuwuYu)).Where("id IN ?", payIds).Updates(&editData).Error
	if err != nil {
		define.Response.ResultFail(c, 10002, err.Error(), "")
		tx.Rollback()
		return
	}
	//完成预约订单
	for _, v := range YueData {
		//回滚用户的优惠券
		//调用修改服务套餐以及明细
		err = EditFuOrder(tx, v)
		if err != nil {
			define.Response.ResultFail(c, 10003, define.JsonDataX, "")
			tx.Rollback()
			return
		}
	}
	tx.Commit() //结束事务
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data":    "成功",
	})
}

// 激活套餐
func ActivationFuOrder(c *gin.Context) {
	var jsonData models.MFuwuOrderLog
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonDataX, "")
		return
	}
	var orderData models.MFuwuOrderLog
	var count int64
	err = models.DB.Model(new(models.MFuwuOrderLog)).Where("id=?", jsonData.ID).Count(&count).First(&orderData).Error
	if err != nil {
		define.Response.ResultFail(c, 10001, define.JsonDataX, "")
		return
	}
	//判断当前订单是否存在以及状态是否为0
	if count < 0 {
		define.Response.ResultFail(c, 10002, "订单未查询到！", "")
		return
	}
	tx := models.DB.Begin() //开启事务
	//修改套餐状态
	err = tx.Model(new(models.MFuwuOrderLog)).Where("id=?", jsonData.ID).Update("status", 2).Error
	if err != nil {
		define.Response.ResultFail(c, 10004, define.JsonDataX, "")
		tx.Rollback()
		return
	}
	//修改服务明细表
	err = tx.Model(new(models.MFuwuOrderGoods)).Where("tid=?", jsonData.ID).Update("status", 1).Error
	if err != nil {
		define.Response.ResultFail(c, 10005, define.JsonDataX, "")
		tx.Rollback()
		return
	}
	//循环判断当前订单所有的套餐是否已经赠送或者激活
	var orderList []models.MFuwuOrderLog
	err = tx.Model(new(models.MFuwuOrderLog)).Where("orderid=?", orderData.Orderid).Find(&orderList).Error
	if err != nil {
		define.Response.ResultFail(c, 10001, define.JsonDataX, "")
		return
	}
	cur11 := true
	for _, v := range orderList {
		if jsonData.ID != v.ID {
			if v.Status == 1 {
				cur11 = false
				break
			}
		}
	}
	if cur11 == true {
		err = tx.Model(new(models.MFuwuOrder)).Where("id=?", orderData.Orderid).Update("status", 6).Error
		if err != nil {
			define.Response.ResultFail(c, 10005, define.JsonDataX, "")
			tx.Rollback()
			return
		}
	}
	tx.Commit() //关闭事务
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data":    "",
		"msg":     "成功！",
	})
}

type FuWuTao struct {
	BusinessData BusinessData             `json:"business_data"`
	MFuwu        models.MFuwuOrderLog     `json:"m_fuwu"`
	OrderGoods   []models.MFuwuOrderGoods `json:"order_goods"`
}

// 获取服务套餐
func GetFuWuTaoList(c *gin.Context) {
	var jsonData Newdata
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonDataX, "")
		return
	}
	var list []models.MFuwuOrderLog
	var count int64
	if jsonData.Page == 0 {
		jsonData.Page = -1
	}
	if jsonData.Limit == 0 {
		jsonData.Limit = -1
	}
	offsetVal := (jsonData.Page - 1) * jsonData.Limit
	if jsonData.Page == -1 && jsonData.Limit == -1 {
		offsetVal = -1
	}
	err = models.DB.Model(new(models.MFuwuOrderLog)).Where("mid=? AND status=? or status=?  or status=?", jsonData.Mid, 2, 3, 4).Count(&count).Limit(jsonData.Limit).Offset(offsetVal).Order("id desc").Find(&list).Error
	if err != nil {
		define.Response.ResultFail(c, 10001, define.JsonDataX, "")
		return
	}
	var ListData []FuWuTao
	for _, v := range list {
		var adminData models.MAdminSet
		err = models.DB.Model(new(models.MAdminSet)).Where("aid=?", v.Aid).Find(&adminData).Error
		if err != nil {
			define.Response.ResultFail(c, 10003, define.JsonDataX, "")
			return
		}
		var taoData []models.MFuwuOrderGoods
		err = models.DB.Model(new(models.MFuwuOrderGoods)).Where("tid=?", v.ID).Find(&taoData).Error
		if err != nil {
			define.Response.ResultFail(c, 10001, define.JsonDataX, "")
			return
		}
		one := FuWuTao{
			MFuwu:      v,
			OrderGoods: taoData,
		}
		one.BusinessData.Logo = adminData.Logo
		one.BusinessData.Name = adminData.Name
		one.BusinessData.Kfurl = adminData.Kfurl
		ListData = append(ListData, one)
	}
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data":    ListData,
		"count":   count,
	})
}

// 确认预约服务
type ConfirmarFuOrder struct {
	Address models.MMemberAddress  `json:"address"`
	Pro     models.MFuwuOrderGoods `json:"pro"`
	FuPro   models.MFuProduct      `json:"fu_pro"`
	Region  []models.MRegion       `json:"region"`
}

func GetFuYueConfirmar(c *gin.Context) {
	var jsonData Newdata
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonDataX, "")
		return
	}
	var returnData ConfirmarFuOrder
	//获取用户的下单地址
	var addressList []models.MMemberAddress
	err = models.DB.Model(new(models.MMemberAddress)).Where("mid=?", jsonData.Mid).Find(&addressList).Error
	if err != nil {
		define.Response.ResultFail(c, 10001, define.JsonDataX, "")
		return
	}
	//判断用户是否有收货地址
	if len(addressList) > 0 {
		cur := false
		//判断用户地址中是否有默认地址
		for _, v := range addressList {
			if v.Isdefault == 1 {
				returnData.Address = v
				cur = true
				break
			}
		}
		//如果没有默认地址，则选第一条地址
		if cur == false {
			returnData.Address = addressList[0]
		}
	}
	//获取商品信息
	var proData models.MFuwuOrderGoods
	err = models.DB.Model(new(models.MFuwuOrderGoods)).Where("id=?", jsonData.Id).First(&proData).Error
	if err != nil {
		define.Response.ResultFail(c, 10002, define.JsonDataX, "")
		return
	}
	var fuData models.MFuProduct
	err = models.DB.Model(new(models.MFuProduct)).Where("id=?", proData.Proid).First(&fuData).Error
	if err != nil {
		define.Response.ResultFail(c, 10003, define.JsonDataX, "")
		return
	}
	var RegionData []models.MRegion
	newArr := strings.Split(fuData.Freightdata, ",")
	var Ids []int
	for _, v := range newArr {
		num, _ := strconv.Atoi(v)
		Ids = append(Ids, num)
	}
	err = models.DB.Model(new(models.MRegion)).Where("id IN ?", Ids).Find(&RegionData).Error
	if err != nil {
		define.Response.ResultFail(c, 10004, define.JsonDataX, "")
		return
	}
	returnData.Pro = proData
	returnData.FuPro = fuData
	returnData.Region = RegionData
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data":    returnData,
	})
}

type MFuwuYuData struct {
	Aid              int    `gorm:"type:int(11);" json:"aid"`                     //会员ID
	Mid              int    `gorm:"type:int(11);" json:"mid"`                     //会员ID
	Xid              int    `gorm:"type:int(11);" json:"xid"`                     //服务套餐项目ID
	AddressId        int    `gorm:"type:int(11);" json:"address_id"`              //地址ID
	YuYueDate        string `gorm:"type:varchar(255);" json:"yu_yue_date"`        //预约日期
	StartDefaultTime string `gorm:"type:varchar(255);" json:"start_default_time"` //预约开始时间
	EndDefaultTime   string `gorm:"type:varchar(255);" json:"end_default_time"`   //预约结束时间
	Remark           string `gorm:"type:varchar(255);" json:"remark"`
}

// 预约下单
func AddFuwuYu(c *gin.Context) {
	var jsonData MFuwuYuData
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonDataX, "")
		return
	}
	//查询项目明细
	var OrderGoods models.MFuwuOrderGoods
	err = models.DB.Model(new(models.MFuwuOrderGoods)).Where("id=?", jsonData.Xid).First(&OrderGoods).Error
	if err != nil {
		define.Response.ResultFail(c, 10001, define.JsonDataX, "")
		return
	}
	//判断项目次数是否足够
	if OrderGoods.Num < OrderGoods.YNum {
		define.Response.ResultFail(c, 10002, "您的服务次数不足！", "")
		return
	}
	//判断下单待用户是否为该服务的拥有者
	if jsonData.Mid != OrderGoods.Mid {
		define.Response.ResultFail(c, 10002, "您无法使用该服务！", "")
		return
	}
	//查询地址
	var AddressData models.MMemberAddress
	err = models.DB.Model(new(models.MMemberAddress)).Where("id=?", jsonData.AddressId).First(&AddressData).Error
	if err != nil {
		define.Response.ResultFail(c, 10003, define.JsonDataX, "")
		return
	}
	//生成邀请码
	CardNumber := time.Now().Format("20060102150405")
	inviteCode1 := CardNumber + string(define.Krand(16, define.KC_RAND_KIND_UPPER))
	var FuwuYu models.MFuwuYu
	FuwuYu.Aid = jsonData.Aid
	FuwuYu.Mid = jsonData.Mid
	FuwuYu.Orderid = OrderGoods.Orderid
	FuwuYu.Tid = OrderGoods.Tid
	FuwuYu.Xid = jsonData.Xid
	FuwuYu.Bid = 0
	FuwuYu.Yid = 0
	FuwuYu.Ordernum = OrderGoods.Ordernum
	FuwuYu.Proid = OrderGoods.Proid
	FuwuYu.Name = OrderGoods.Name
	FuwuYu.Num = OrderGoods.Num
	FuwuYu.YNum = OrderGoods.YNum + 1
	FuwuYu.CostPrice = OrderGoods.CostPrice
	FuwuYu.SellPrice = OrderGoods.SellPrice
	FuwuYu.Status = 0
	FuwuYu.Createtime = int(time.Now().Unix())
	FuwuYu.Endtime = 0
	FuwuYu.JieTime = 0
	FuwuYu.Linkman = AddressData.Name
	FuwuYu.Tel = AddressData.Tel
	FuwuYu.Province = AddressData.Province
	FuwuYu.City = AddressData.City
	FuwuYu.District = AddressData.District
	FuwuYu.Area = AddressData.Area
	FuwuYu.Address = AddressData.Address
	FuwuYu.HouseNumber = AddressData.HouseNumber
	FuwuYu.Latitude = AddressData.Latitude
	FuwuYu.Longitude = AddressData.Longitude
	FuwuYu.YuYueDate = jsonData.YuYueDate
	FuwuYu.StartDefaultTime = jsonData.StartDefaultTime
	FuwuYu.EndDefaultTime = jsonData.EndDefaultTime
	FuwuYu.Remark = jsonData.Remark
	FuwuYu.HexiaoCode = inviteCode1
	FuwuYu.YyueOrder = CardNumber
	//设置预约时间戳
	srt := jsonData.YuYueDate + " " + jsonData.StartDefaultTime + ":00"
	FuwuYu.YuYueTime = int(define.TimeUnix(srt))
	//开启事务
	tx := models.DB.Begin()
	//新增服务记录
	err = tx.Create(&FuwuYu).Error
	if err != nil {
		define.Response.ResultFail(c, 10003, define.JsonDataX, "")
		tx.Rollback()
		return
	}
	//修改项目明细状态以及数量
	var EditData = map[string]interface{}{
		"status": 2,
		"y_num":  gorm.Expr("y_num+?", 1),
	}
	err = tx.Model(new(models.MFuwuOrderGoods)).Where("id=?", jsonData.Xid).Updates(&EditData).Error
	if err != nil {
		define.Response.ResultFail(c, 10004, define.JsonDataX, "")
		tx.Rollback()
		return
	}
	//修改套餐状态
	err = tx.Model(new(models.MFuwuOrderLog)).Where("id=?", OrderGoods.Tid).Update("status", 3).Error
	if err != nil {
		define.Response.ResultFail(c, 10005, define.JsonDataX, "")
		tx.Rollback()
		return
	}
	//发送预约
	AddSmsModel(1, CardNumber)
	tx.Commit()
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data":    "成功！",
	})
}

// 获取服务清单列表
func GetFuYuList(c *gin.Context) {
	var jsonData Newdata
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonDataX, "")
		return
	}
	var list []models.MFuwuYu
	var count int64
	if jsonData.Page == 0 {
		jsonData.Page = -1
	}
	if jsonData.Limit == 0 {
		jsonData.Limit = -1
	}
	offsetVal := (jsonData.Page - 1) * jsonData.Limit
	if jsonData.Page == -1 && jsonData.Limit == -1 {
		offsetVal = -1
	}
	err = models.DB.Model(new(models.MFuwuYu)).Where("mid=?", jsonData.Mid).Count(&count).Limit(jsonData.Limit).Offset(offsetVal).Order("id desc").Find(&list).Error
	if err != nil {
		define.Response.ResultFail(c, 10001, define.JsonDataX, "")
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data":    list,
		"count":   count,
	})
}

type FuYuShow struct {
	FuYu   models.MFuwuYu   `json:"fu_yu"`
	Region []models.MRegion `json:"region"`
}

// 获取预约详情
func GetFuYuShow(c *gin.Context) {
	var jsonData Newdata
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonDataX, "")
		return
	}
	var ShowData models.MFuwuYu
	err = models.DB.Model(new(models.MFuwuYu)).Where("id=?", jsonData.Id).First(&ShowData).Error
	if err != nil {
		define.Response.ResultFail(c, 10001, define.JsonDataX, "")
		return
	}
	//查询商品
	var fuData models.MFuProduct
	err = models.DB.Model(new(models.MFuProduct)).Where("id=?", ShowData.Proid).First(&fuData).Error
	if err != nil {
		define.Response.ResultFail(c, 10003, define.JsonDataX, "")
		return
	}
	var RegionData []models.MRegion
	newArr := strings.Split(fuData.Freightdata, ",")
	var Ids []int
	for _, v := range newArr {
		num, _ := strconv.Atoi(v)
		Ids = append(Ids, num)
	}
	err = models.DB.Model(new(models.MRegion)).Where("id IN ?", Ids).Find(&RegionData).Error
	if err != nil {
		define.Response.ResultFail(c, 10004, define.JsonDataX, "")
		return
	}
	var listData FuYuShow
	listData.FuYu = ShowData
	listData.Region = RegionData
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data":    listData,
	})
}

// 修改预约
func EditFuYu(c *gin.Context) {
	var jsonData models.MFuwuYu
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonDataX, "")
		return
	}
	var data models.MFuwuYu
	err = models.DB.Model(new(models.MFuwuYu)).Where("id=?", jsonData.ID).First(&data).Error
	if err != nil {
		define.Response.ResultFail(c, 10001, define.JsonDataX, "")
		return
	}
	//判断当前时间是否扣除次数
	srt := data.YuYueDate + " " + data.StartDefaultTime + ":00"
	Sum := time.Now().Unix() + (60 * 60 * 3)
	if Sum > define.TimeUnix(srt) { //判断服务时间小于3小时
		define.Response.ResultFail(c, 10001, "预约时间小于3小时，无法修改！", "")
		return
	}
	sss := jsonData.YuYueDate + " " + jsonData.StartDefaultTime + ":00"
	var EditData = map[string]interface{}{
		"linkman":            jsonData.Linkman,
		"tel":                jsonData.Tel,
		"province":           jsonData.Province,
		"city":               jsonData.City,
		"district":           jsonData.District,
		"area":               jsonData.Area,
		"address":            jsonData.Address,
		"house_number":       jsonData.HouseNumber,
		"latitude":           jsonData.Latitude,
		"longitude":          jsonData.Longitude,
		"yu_yue_date":        jsonData.YuYueDate,
		"start_default_time": jsonData.StartDefaultTime,
		"end_default_time":   jsonData.EndDefaultTime,
		"remark":             jsonData.Remark,
		"yu_yue_time":        int(define.TimeUnix(sss)),
	}
	err = models.DB.Model(new(models.MFuwuYu)).Where("id=?", jsonData.ID).Updates(&EditData).Error
	if err != nil {
		define.Response.ResultFail(c, 10002, define.JsonDataX, "")
		return
	}

	//发送预约
	AddSmsModel(2, data.YyueOrder)
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data":    define.Success,
	})
}

// 取消预约
func CancelFuwuYu(c *gin.Context) {
	var jsonData models.MFuwuYu
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonDataX, "")
		return
	}
	var data models.MFuwuYu
	err = models.DB.Model(new(models.MFuwuYu)).Where("id=?", jsonData.ID).First(&data).Error
	if err != nil {
		define.Response.ResultFail(c, 10001, define.JsonDataX, "")
		return
	}
	//判断当前时间是否扣除次数
	srt := data.YuYueDate + " " + data.StartDefaultTime + ":00"
	Sum := time.Now().Unix() + (60 * 60 * 3)
	fmt.Println(srt)
	fmt.Println(Sum)
	tx := models.DB.Begin()
	if Sum > define.TimeUnix(srt) { //判断服务时间小于3小时
		//正常扣除次数
		//修改订单状态取消
		err = tx.Model(new(models.MFuwuYu)).Where("id=?", jsonData.ID).Update("status", 4).Error
		if err != nil {
			define.Response.ResultFail(c, 10002, define.JsonDataX, "")
			tx.Rollback()
			return
		}
		fmt.Println(111)
		//调用修改服务套餐以及明细
		err = EditFuOrder(tx, data)
		if err != nil {
			define.Response.ResultFail(c, 10003, define.JsonDataX, "")
			tx.Rollback()
			return
		}
	} else { //大于3小时
		//修改订单状态取消
		err = tx.Model(new(models.MFuwuYu)).Where("id=?", jsonData.ID).Update("status", 4).Error
		if err != nil {
			define.Response.ResultFail(c, 10004, define.JsonDataX, "")
			tx.Rollback()
			return
		}
		//回滚次数
		//修改服务次数
		var editDataGoos = map[string]interface{}{
			"y_num":  gorm.Expr("y_num-?", 1),
			"status": 1,
		}
		err = tx.Model(new(models.MFuwuOrderGoods)).Where("id=?", data.Xid).Updates(&editDataGoos).Error
		if err != nil {
			define.Response.ResultFail(c, 10005, define.JsonDataX, "")
			tx.Rollback()
			return
		}
		//修改套餐的状态
		err = tx.Model(new(models.MFuwuOrderLog)).Where("id=?", data.Tid).Update("status", 2).Error
		if err != nil {
			define.Response.ResultFail(c, 10005, define.JsonDataX, "")
			tx.Rollback()
			return
		}
	}
	//发送预约
	AddSmsModel(3, data.YyueOrder)
	tx.Commit()
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data":    define.Success,
	})
}

// 修改订单状态取消
func EditFuOrder(tx *gorm.DB, data models.MFuwuYu) error {
	//查询服务明细表
	var TData models.MFuwuOrderGoods
	err := tx.Model(new(models.MFuwuOrderGoods)).Where("id=?", data.Xid).First(&TData).Error
	if err != nil {
		return err
	}
	//查询套餐表
	var TCData []models.MFuwuOrderGoods
	err = tx.Model(new(models.MFuwuOrderGoods)).Where("id=?", data.Tid).Find(&TCData).Error
	if err != nil {
		return err
	}
	//判断当前下面的套餐是否已经全部结束
	cur := true
	for _, v := range TCData {
		if TData.ID != v.ID {
			if v.Num > v.YNum {
				cur = false
				break
			}
		}
	}
	//判断当前剩余次数是否已经用完
	if TData.Num > TData.YNum {
		//修改套餐表状态
		err = tx.Model(new(models.MFuwuOrderLog)).Where("id=?", data.Tid).Update("status", 2).Error
		if err != nil {
			return err
		}
		//修改服务明细表状态
		var editDataGoos = map[string]interface{}{
			"status": 1,
		}
		err = tx.Model(new(models.MFuwuOrderGoods)).Where("id=?", data.Xid).Updates(&editDataGoos).Error
		if err != nil {
			return err
		}
	} else {
		//修改服务明细表状态
		var editDataGoos = map[string]interface{}{
			"status": 3,
		}
		err = tx.Model(new(models.MFuwuOrderGoods)).Where("id=?", data.Xid).Updates(&editDataGoos).Error
		if err != nil {
			return err
		}
	}
	if cur {
		//修改套餐表状态
		err = tx.Model(new(models.MFuwuOrderLog)).Where("id=?", data.Tid).Update("status", 4).Error
		if err != nil {
			return err
		}
	}
	//查询套餐表
	var TClist []models.MFuwuOrderLog
	err = tx.Model(new(models.MFuwuOrderLog)).Where("orderid=?", data.Orderid).Find(&TClist).Error
	if err != nil {
		return err
	}
	cur11 := true
	for _, v := range TClist {
		if TData.Tid != v.ID {
			if v.Status != 4 {
				cur11 = false
				break
			}
		}
	}
	if cur11 {
		//修改套餐表状态
		err = tx.Model(new(models.MFuwuOrder)).Where("id=?", data.Orderid).Update("status", 8).Error
		if err != nil {
			return err
		}
	}
	return nil
}

// 赠送套餐
func GiveFuOrder(c *gin.Context) {
	var jsonData models.MFuwuOrderLog
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonDataX, "")
		return
	}
	//查询套餐信息
	var OrderData models.MFuwuOrderLog
	err = models.DB.Model(new(models.MFuwuOrderLog)).Where("id=?", jsonData.ID).First(&OrderData).Error
	if err != nil {
		define.Response.ResultFail(c, 10001, define.JsonDataX, "")
		return
	}
	tx := models.DB.Begin()
	//写入赠送表
	srt := ""
	if OrderData.ZhuanId == "" {
		srt = strconv.Itoa(OrderData.Mid)
	} else {
		srt = OrderData.ZhuanId + "," + strconv.Itoa(OrderData.Mid)
	}
	var giveOrder models.MFuwuGiveLog
	giveOrder.Pic = OrderData.Pic
	giveOrder.Name = OrderData.Name
	giveOrder.Orderid = OrderData.Orderid
	giveOrder.Ordernum = OrderData.Ordernum
	giveOrder.Tid = OrderData.ID
	giveOrder.Ggid = OrderData.Ggid
	giveOrder.Ggname = OrderData.Ggname
	giveOrder.Proid = OrderData.Proid
	giveOrder.Status = OrderData.Status
	giveOrder.Type = 1
	giveOrder.Barcode = OrderData.Barcode
	giveOrder.ZhuanMid = OrderData.Mid
	giveOrder.ZhuanId = srt
	giveOrder.ProductPrice = OrderData.ProductPrice
	giveOrder.Createtime = int(time.Now().Unix())
	giveOrder.HexiaoCode = OrderData.HexiaoCode
	giveOrder.Mid = OrderData.Mid
	err = tx.Create(&giveOrder).Error
	if err != nil {
		define.Response.ResultFail(c, 10002, define.JsonDataX, "")
		tx.Rollback()
		return
	}
	var SongOrder models.MFuwuGiveLog
	SongOrder.Pic = OrderData.Pic
	SongOrder.Name = OrderData.Name
	SongOrder.Orderid = OrderData.Orderid
	SongOrder.Ordernum = OrderData.Ordernum
	SongOrder.Tid = OrderData.ID
	SongOrder.Ggid = OrderData.Ggid
	SongOrder.Ggname = OrderData.Ggname
	SongOrder.Proid = OrderData.Proid
	SongOrder.Status = OrderData.Status
	SongOrder.Type = 2
	SongOrder.Barcode = OrderData.Barcode
	SongOrder.ZhuanMid = OrderData.Mid
	SongOrder.ZhuanId = srt
	SongOrder.ProductPrice = OrderData.ProductPrice
	SongOrder.Createtime = int(time.Now().Unix())
	SongOrder.HexiaoCode = OrderData.HexiaoCode
	SongOrder.Mid = jsonData.ID
	err = tx.Create(&SongOrder).Error
	if err != nil {
		define.Response.ResultFail(c, 10003, define.JsonDataX, "")
		tx.Rollback()
		return
	}
	//循环判断当前订单所有的套餐是否已经赠送或者激活
	var orderList []models.MFuwuOrderLog
	err = tx.Model(new(models.MFuwuOrderLog)).Where("orderid=?", OrderData.Orderid).Find(&orderList).Error
	if err != nil {
		define.Response.ResultFail(c, 10004, define.JsonDataX, "")
		return
	}
	cur11 := true
	for _, v := range orderList {
		if jsonData.ID != v.ID {
			if v.Status == 1 {
				cur11 = false
				break
			}
		}
	}
	if cur11 == true {
		err = tx.Model(new(models.MFuwuOrder)).Where("id=?", OrderData.Orderid).Update("status", 6).Error
		if err != nil {
			define.Response.ResultFail(c, 10005, define.JsonDataX, "")
			tx.Rollback()
			return
		}
	}
	tx.Commit() //关闭事务
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data":    "",
		"msg":     "成功！",
	})
}

// 获取我的预约服务
func GetYueList(c *gin.Context) {
	var jsonData models.MFuwuYu
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonDataX, "")
		return
	}
	var list []models.MFuwuYu
	err = models.DB.Model(new(models.MFuwuYu)).Where("mid=? AND status<?", jsonData.Mid, 3).Find(&list).Error
	if err != nil {
		define.Response.ResultFail(c, 10001, define.JsonDataX, "")
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data":    list,
	})
}
